package com.basic.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * ClassName: StringUtils
 * Package: com.basic.backstage
 * Description:
 *          Download Util
 * @Author: Night
 * @Create: 2023/12/7 - 13:55
 * @Version: 1.0
 */
public class DownUtils {
    /**
     *  Download the given resource path
     * @param request HttpServletRequest
     * @return responseEntity
     */
    public static ResponseEntity downLoad(HttpServletRequest request) throws IOException {
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        // 将JSON字符串解析为Map
        Map<String, String> jsonMap = objectMapper.readValue(json, Map.class);
        String url = jsonMap.get("url");
        String fileName = jsonMap.get("fileName");
//        url = "D:"+ File.separator+"modify"+File.separator+"dist"+File.separator+url;
        //判断URL返回是否为空
        if (StringUtils.hasLength(url)){
            File file = new File(url);
            //判断资源是否存在
            if (!file.exists()){
                throw new RuntimeException("The resource does not exist or has changed");
            }
            try (FileInputStream fis = new FileInputStream(file)){
                byte[] download = new byte[fis.available()];
                fis.read(download);
                // 获取浏览器名称
                String agent = request.getHeader("user-agent");
                // 不同浏览器需要对文件名做特殊处理
                String fileNames = encodeFileName(agent,fileName);
                //封装为ResponseEntity
                MultiValueMap<String,String> headers = new HttpHeaders();
                headers.add("Content-Disposition","attachment;filename="+ fileNames);
                // System.err.println(fileName);
                HttpStatus statusCode = HttpStatus.OK;
                ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(download, headers, statusCode);
                return responseEntity;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("The resource path is empty");
    }

    public static ResponseEntity downLoad(String url, String fileName, HttpServletRequest request){
        //判断URL返回是否为空
        if (StringUtils.hasLength(url)){
            File file = new File(url);
            //判断资源是否存在
            if (!file.exists()){
                throw new RuntimeException("The resource does not exist or has changed");
            }
            try (FileInputStream fis = new FileInputStream(file)){
                byte[] download = new byte[fis.available()];
                fis.read(download);
                // 获取浏览器名称
                String agent = request.getHeader("user-agent");
                // 不同浏览器需要对文件名做特殊处理
                String fileNames = encodeFileName(agent, fileName);
                // System.err.println(fileNames);
                //封装为ResponseEntity
                MultiValueMap<String,String> headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileNames);
                headers.add("Content-Type", "application/octet-stream");
                ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(download, headers, HttpStatus.OK);
                return responseEntity;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("The resource path is empty");
    }

    private static String encodeFileName(String userAgent, String fileName) throws UnsupportedEncodingException {
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            // IE浏览器
            //  new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            return URLEncoder.encode(fileName, "UTF-8").replace("+", " ");
        } else if (userAgent.contains("Edge") || userAgent.contains("Edg")) {
            // Edge浏览器
            return URLEncoder.encode(fileName, "UTF-8");
        } else if (userAgent.contains("Chrome")) {
            // Chrome浏览器
            return new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        } else if (userAgent.contains("Firefox")) {
            // Firefox浏览器
            return "=?UTF-8?B?" + Base64.getEncoder().encodeToString(fileName.getBytes(StandardCharsets.UTF_8)) + "?=";
        } else {
            // 其他浏览器（如Safari）统一使用UTF-8编码
            return new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
    }

}